package com.atguigu.junit;


import com.atguigu.pojo.Customer;
import com.atguigu.pojo.Order;
import com.atguigu.utils.DBUtils;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.List;

/**
 * @author hjwStrart
 * @time 2022-03-05 17:23
 */
public class testDRUD {
    public static void main(String[] args) {
        try {
            test3();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void test6() throws Exception {
        String sql = "delete from customers where name = ?";
        int result = DBUtils.update(sql, "test");
        System.out.println(result);
        DBUtils.closeResource();
    }
    public static void test5(){
        try {
            List<Customer> customers = DBUtils.queryForList(Customer.class, "select id,name,email,birth from customers where id < ?", 5);
            customers.forEach(System.out :: println);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtils.closeResource();
        }
    }


    public static void test4(){
        try {
            Customer customer = DBUtils.queryForOne(Customer.class, "select id,name,email,birth from customers where id = ?", 1);
            System.out.println(customer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询customers表中的记录
     */
    public static void test1() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            String sql = "select * from customers where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,1);
            rs = ps.executeQuery();
            if (rs.next()) {
                //            在java程序中，和数据库交互的方法，一旦涉及到索引一般是从一开始
                //            在源码中的的注释：columnIndex – the first column is 1, the second is 2, ...
                System.out.println(rs.getObject(1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtils.closeResource();
        }
    }

    /**
     *查询customers表中的记录
     */
    public static void test2(){
//            注意当表名是关键字时，回报错。order 是排序关键词。使用着重号包裹起来。``
            String sql = "select id,name,email,birth from `customers` where id = ?";
        System.out.println(DBUtils.queryForOne(Customer.class, sql, 1));
    }

    /**
     * 询order表中的记录,并将记录封装为对象。
     */
    public static void test3() {

//            注意当表名是关键字时，回报错。order 是排序关键词。使用着重号包裹起来。``
//            String sql = "select * from `order` where order_id = ?";orm映射失败，类字段和表字段对映不上！！！解决方案：使用别名
            String sql = "select order_id orderId,order_name orderName,order_date orderDate from `order` where order_id = ?";

        System.out.println(DBUtils.queryForOne(Order.class, sql, 1));
    }

}
